/*
package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.GoodsEntity;
import com.quanshu.exchange.support.entity.ShoppingCarEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseSubscriber;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.web_page.SettleAccountActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

*/
/**
 * 购物车
 * Created by xiniu003 on 2018/1/8.
 *//*


public class ShopTrolleyActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.edit_comment)
    TextView editComment;
    @BindView(R.id.shop_trolley_recy)
    RecyclerView shopTrolleyRecy;
    @BindView(R.id.shop_trolley_null)
    LinearLayout shopTrolleyNull;
    @BindView(R.id.shop_trolley_all_image)
    ImageView shopTrolleyAllImage;
    @BindView(R.id.shop_trolley_all_llt)
    LinearLayout shopTrolleyAllLlt;
    @BindView(R.id.shop_trolley_delete)
    TextView shopTrolleyDelete;
    @BindView(R.id.shop_trolley_zongji_pianyi)
    TextView shopTrolleyZongjiPianyi;
    @BindView(R.id.shop_trolley_zongji_gui)
    TextView shopTrolleyZongjiGui;
    @BindView(R.id.shop_trolley_zongji_llt)
    LinearLayout shopTrolleyZongjiLlt;

    private ShoppingCarEntity datas;
    private SingleAdapter<GoodsEntity> adapter;

    private int tmpNmus;//商品数量中间值 - 最终值

    private int differenceValue = 0;//商品原始数量 与 加减之后的差值

    private double totalPrice = 0.00; // 商品总价

    private double mianfeiPrice = 0.00;

    private String[] goodsIdArray;//商品一维数组

    private DecimalFormat df = new DecimalFormat("0.00");//转化成为两位小数;
    */
/**
     * 批量模式下，用来记录当前选中状态,记录--订单ID"goods_order_id"
     *//*

    private SparseArray<Boolean> mSelectState = new SparseArray<Boolean>();

    */
/**
     *
     *//*

    private SparseArray<Boolean> sparseArray = new SparseArray<Boolean>();

    private int flag = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_trolley);
        ButterKnife.bind(this);

        df.format(totalPrice);

        initAdapter();
        getMyCart();
        mSelectState.clear();
        initListener();
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        //编辑 or完成 按钮事件
        RxViewHelper.getInstance().clicks(editComment, aVoid -> {

            setUseStatus();//设置使用状态
        });

        //点击全选
        RxViewHelper.getInstance().clicks(shopTrolleyAllLlt, aVoid -> {

            doCheckAll();//全选操作

        });

        //去结算 or 删除 事件
        RxViewHelper.getInstance().clicks(shopTrolleyDelete, aVoid -> {

            if (getSelectedIds().size() > 0) {

                if (shopTrolleyDelete.getText().toString().equals("去结算")) {
                    ToastHelper.toast("你去结算就好了啊");

                    //做结算操作时，须将String[]转为json字符串
                    Gson gson = new Gson();
                    String goodsIdTypeNumsServiceString = gson.toJson(getGoodsIdTypeNumsServiceArray());
                    Log.e("888888888", goodsIdTypeNumsServiceString);
                    Intent intent = new Intent(ShopTrolleyActivity.this, SettleAccountActivity.class);
                    intent.putExtra("SETTLE_ACCOUNT", goodsIdTypeNumsServiceString);
                    startActivity(intent);


                } else {
                    getRemoveCart();//批量删除
                }


            } else {
                ToastHelper.toast("您还未勾选商品！");
            }

        });
    }

    //全选操作
    private void doCheckAll() {

        if (adapter != null) {
            if (mSelectState.size() == 0 || (mSelectState.size() != adapter.getData().size())) {
                totalPrice = 0.00;
                mSelectState.clear();
                int dataSize = adapter.getData().size();
                if (dataSize == 0) {
                    return;
                }
                for (int i = 0; i < dataSize; i++) {
                    int _id = i;
                    mSelectState.put(_id, true);
                    totalPrice = totalPrice +
                            Double.valueOf(adapter.getData().get(i).getSell_price()) *
                                    adapter.getData().get(i).getCount();
                }
                shopTrolleyAllImage.setSelected(true);
            } else if (mSelectState.size() == adapter.getData().size()) {
                mSelectState.clear();
                totalPrice = 0.00;
                shopTrolleyAllImage.setSelected(false);
            }
            shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
            adapter.notifyDataSetChanged();
        }

//        if (editComment.getText().toString().equals("编辑")) {//结算

//        } else {//删除
//            if (adapter != null) {
//                if (mSelectState.size() == 0 || (mSelectState.size() != adapter.getData().size())) {
//                    mSelectState.clear();
//                    int dataSize = adapter.getData().size();
//                    if (dataSize == 0) {
//                        return;
//                    }
//                    for (int i = 0; i < dataSize; i++) {
//                        int _id = i;
//                        mSelectState.put(_id, true);
//                        totalPrice = totalPrice +
//                                Double.valueOf(adapter.getData().get(i).getSell_price()) *
//                                        adapter.getData().get(i).getCount();
//                    }
//                    shopTrolleyAllImage.setSelected(true);
//                } else if (mSelectState.size() == adapter.getData().size()) {
//                    mSelectState.clear();
//                    totalPrice = 0.00;
//                    shopTrolleyAllImage.setSelected(false);
//                }
//                shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
//                adapter.notifyDataSetChanged();
//            }
//        }
    }

    //设置使用状态
    private void setUseStatus() {
        if (editComment.getText().toString().equals("编辑")) {

            shopTrolleyZongjiLlt.setVisibility(View.GONE);
            editComment.setText("完成");
            shopTrolleyDelete.setText("删除");

        } else {

            shopTrolleyZongjiLlt.setVisibility(View.VISIBLE);
            editComment.setText("编辑");
            shopTrolleyDelete.setText("去结算");
        }
    }

    //结算 or删除时，选中多少件商品
    private final List<Integer> getSelectedIds() {
        ArrayList<Integer> selectedIds = new ArrayList<Integer>();
        for (int index = 0; index < mSelectState.size(); index++) {
            if (mSelectState.valueAt(index)) {
                selectedIds.add(mSelectState.keyAt(index));
            }
        }
        return selectedIds;
    }

    //结算时  有多少件商品，勾选了 我要免费
    private final List<Integer> getLength() {
        ArrayList<Integer> selectedIds = new ArrayList<Integer>();
        for (int i = 0; i < sparseArray.size(); i++) {
            if (sparseArray.valueAt(i)) {
                selectedIds.add(sparseArray.keyAt(i));
            }
        }
        return selectedIds;
    }

    //根据下标，拿到goods_id 与 goods_type，拼成String[],用于批量删除
    private final String[] getGoodsIdTypeArray() {
        List<Integer> select_pos = getSelectedIds();
        ArrayList<String> goodsId = new ArrayList<String>();
        for (int i = 0; i < select_pos.size(); i++) {
            goodsId.add(adapter.getData().get(select_pos.get(i)).getGoods_id() +
                    "," +
                    adapter.getData().get(select_pos.get(i)).getGoods_type());
        }

        goodsIdArray = goodsId.toArray(new String[goodsId.size()]);
        Log.e("12345678goodsIdArray", goodsIdArray + "");
        return goodsIdArray;
    }

    private String[] goodsIdTypeNumsServiceArray;

    //根据下标，拿到goods_id 与 goods_type 与 num 与 is_service，拼成String[],用于批量结算
    private String[] getGoodsIdTypeNumsServiceArray() {
        List<Integer> select_pos = getSelectedIds();
        List<Integer> seleect_minfei = getLength();

        List<Integer> pos = new ArrayList<Integer>();//勾选我要免费
        List<Integer> pos_ = new ArrayList<Integer>();//不

        ArrayList<String> goodsId = new ArrayList<String>();

        for (int i = 0; i < select_pos.size(); i++) {

            for (int j = 0; j < seleect_minfei.size(); j++) {

                if (select_pos.get(i) == seleect_minfei.get(j)) {

                    pos.add(select_pos.get(i));

                } else {
                    pos_.add(select_pos.get(i));
                }

            }
        }

        for (int i = 0; i < pos.size(); i++) {
            adapter.getData().get(pos.get(i)).setIs_service("1");
            goodsId.add(adapter.getData().get(pos.get(i)).getGoods_id() + "," +
                    adapter.getData().get(pos.get(i)).getGoods_type() + "," +
                    adapter.getData().get(pos.get(i)).getCount() + "," +
                    adapter.getData().get(pos.get(i)).getIs_service());
        }

        for (int i = 0; i < pos_.size(); i++) {
            adapter.getData().get(pos_.get(i)).setIs_service("0");
            goodsId.add(adapter.getData().get(pos_.get(i)).getGoods_id() + "," +
                    adapter.getData().get(pos_.get(i)).getGoods_type() + "," +
                    adapter.getData().get(pos_.get(i)).getCount() + "," +
                    adapter.getData().get(pos_.get(i)).getIs_service());
        }

        goodsIdTypeNumsServiceArray = goodsId.toArray(new String[goodsId.size()]);
        Log.e("12345678ServiceArray", goodsIdTypeNumsServiceArray + "");
        return goodsIdTypeNumsServiceArray;
    }

    private void initAdapter() {
        shopTrolleyRecy.setLayoutManager(new LinearLayoutManager(ShopTrolleyActivity.this));
        adapter = new SingleAdapter<>(new DataDisplayer<GoodsEntity>(ShopTrolleyActivity.this,
                R.layout.item_shop_trolley) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<GoodsEntity> wrapper,
                                 GoodsEntity item,
                                 int position) {

                item.setTwo_price(String.valueOf(Double.valueOf(item.getSell_price()) * 2));

                holder.setImageUrl(R.id.shop_trolley_shop_image,
                        Config.URL_HOST_SHOP + item.getImg(),
                        R.drawable.default_avatar);
                holder.setText(R.id.shop_trolley_shop_name, item.getName());
                holder.setText(R.id.shop_trolley_shop_bianhao, "商品编号：" + item.getGoods_no());
                holder.setText(R.id.shop_trolley_shop_price_j, item.getSell_price());
                holder.setText(R.id.shop_trolley_shop_price_r, "￥" + item.getSell_price());
                TextView shopPriceR = holder.getView(R.id.shop_trolley_shop_price_r);
                shopPriceR.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.setText(R.id.shop_trolley_shop_number, "x" + item.getCount());

                //商品数量 - 增 - 减
                holder.setOnClickListener(R.id.shop_trolley_shop_edit, view -> {
                    doShowDialog(item, position);

                });

                ImageView imageView = holder.getView(R.id.shop_trolley_select_image);

                int _id_ = position;
                boolean _selected = mSelectState.get(_id_, false);
                if (_selected) {
                    imageView.setSelected(true);
                } else {
                    imageView.setSelected(false);
                }

                ImageView mianfei_image = holder.getView(R.id.mianfei_image);
                holder.setOnClickListener(R.id.mianfei_select, view -> {

                    doCheckMianFei(holder, position, mianfei_image, item);

                });

                //判断是否有勾选商品 -
                if (mSelectState.size() > 0) {
                    shopTrolleyDelete.setBackgroundColor(Color.parseColor("#F8DCB0"));
                } else {
                    shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                }


                //勾选商品
                holder.setOnClickListener(R.id.all_shop_trolley, (View view) -> {

                    doCheck(holder, position, imageView, mianfei_image, item);//勾选商品
                });
            }
        });
        shopTrolleyRecy.setAdapter(adapter);
    }

    //勾选 免费
    private void doCheckMianFei(BaseViewHolder holder, int position, ImageView imageView, GoodsEntity item) {

        int _id = position;
        boolean selected = !sparseArray.get(_id, false);

        boolean selector = mSelectState.get(_id, false);

        if (selector) {//此商品已勾选 - 模式
            //判断此商品是否勾选免费 -
            if (selected) {
                imageView.setSelected(true);
                sparseArray.put(_id, true);
                holder.setVisibility(R.id.mianfei_price, View.VISIBLE);
                holder.setText(R.id.mianfei_price, "+" + item.getSell_price());
                totalPrice = totalPrice + Double.valueOf(item.getSell_price()) * item.getCount();
            } else {
                imageView.setSelected(false);
                sparseArray.delete(_id);
                holder.setVisibility(R.id.mianfei_price, View.GONE);
                totalPrice = totalPrice - Double.valueOf(item.getSell_price()) * item.getCount();
            }

            shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
        } else {//未勾选 - 模式

            ToastHelper.toast("请先勾选此商品");
        }


    }


    //勾选商品
    private void doCheck(BaseViewHolder holder, int position, ImageView imageView, ImageView mianfei, GoodsEntity item) {
        int _id = position;
        boolean selected = !mSelectState.get(_id, false);

        boolean selector = sparseArray.get(_id, false);

        //判断此商品是否被勾选 -
        if (selected) {
            imageView.setSelected(true);
            mSelectState.put(_id, true);
            totalPrice = totalPrice + Double.valueOf(item.getSell_price()) * item.getCount();
        } else {
            imageView.setSelected(false);

            if (selector) {
                mianfei.setSelected(false);
                holder.setVisibility(R.id.mianfei_price, View.GONE);
                totalPrice = totalPrice - Double.valueOf(item.getSell_price()) * item.getCount();
            } else {

            }

            mSelectState.delete(_id);
            totalPrice = totalPrice - Double.valueOf(item.getSell_price()) * item.getCount();
        }

        //判断是否有勾选商品 -
        if (mSelectState.size() > 0) {
            shopTrolleyDelete.setBackgroundColor(Color.parseColor("#F8DCB0"));
        } else {
            shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
        }

        shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));

        //判断是否全选 -
        if (mSelectState.size() == adapter.getData().size()) {
            shopTrolleyAllImage.setSelected(true);
        } else {
            shopTrolleyAllImage.setSelected(false);
        }

    }

    //商品数量 加 - 减
    private void doShowDialog(GoodsEntity item, int position) {
        DialogAddReduce dialogAddReduce = new DialogAddReduce(ShopTrolleyActivity.this);
        dialogAddReduce.show();

        tmpNmus = item.getCount();
        dialogAddReduce.setNums(item.getCount());

        //减少
        dialogAddReduce.getReduceBehaviorSubject().subscribe(reduceShop -> {

            if (tmpNmus > 1) {
                tmpNmus = tmpNmus - 1;
                dialogAddReduce.setNums(tmpNmus);
            } else {
                dialogAddReduce.setNums(tmpNmus);
                ToastHelper.toast("购买数量最小为1个");
            }
        });


        //增加
        dialogAddReduce.getAddBehaviorSubject().subscribe(addShop -> {

            tmpNmus++;
            dialogAddReduce.setNums(tmpNmus);
        });

        //确定
        dialogAddReduce.getOneBehaviorSubject().subscribe(shopEnter -> {

            differenceValue = tmpNmus - item.getCount();
            getIncreCart(item, tmpNmus);
            dialogAddReduce.dismiss();

        });
    }

    //勾选状态下 - 改变购买数量 - 总计 改变
    private void doCheckStatusEditNums() {

        List<Integer> selectedIds = getSelectedIds();

        if (mSelectState.size() != 0) {
            totalPrice = 0.00;
            for (int i = 0; i < selectedIds.size(); i++) {

                totalPrice = totalPrice +
                        Double.valueOf(adapter.getData().get(selectedIds.get(i)).getSell_price()) *
                                adapter.getData().get(selectedIds.get(i)).getCount();

            }
//            shopTrolleyAllImage.setSelected(true);
        }
//        else if (mSelectState.size() == adapter.getData().size()) {
//            mSelectState.clear();
//            totalPrice = 0.00;
//            shopTrolleyAllImage.setSelected(false);
//        }
        shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
    }

    @Override
    protected void onResume() {
        super.onResume();
        getMyCart();
        initAdapter();
        mSelectState.clear();
//        sparseArray.clear();
        totalPrice = 0.00;
        shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
    }

    //获取购物车列表
    private void getMyCart() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getMyCart(String.valueOf(currentUser.getUser_id()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseSubscriber<BaseResponse<ShoppingCarEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ShoppingCarEntity> response) {

                        if (response.getData() != null && response.getData().getGoodsList().size() > 0) {
                            shopTrolleyNull.setVisibility(View.GONE);
                            datas = response.getData();
                            adapter.setData(datas.getGoodsList());
                            if (flag == 1) {//数量 增加 or 减少
                                doCheckStatusEditNums();
                            }

                        } else {
                            mSelectState.clear();
                            shopTrolleyNull.setVisibility(View.VISIBLE);
                            shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                            shopTrolleyAllImage.setSelected(false);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    */
/**
     * 购买车商品数量增加或者减少 - 增加or减少
     *
     * @param item
     * @param value ​增加或减少的数量
     *//*

    private void getIncreCart(GoodsEntity item, int value) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getIncreCart(String.valueOf(currentUser.getUser_id()),
                        item.getGoods_id(),
                        item.getGoods_type(),
                        value)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        flag = 1;
                        getMyCart();
                        adapter.notifyDataSetChanged();

                        ToastHelper.toast(response.getMsg());
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }


    //批量删除
    private void getRemoveCart() {
        //做删除操作时，须将String[]转为json字符串
        Gson gson = new Gson();
        String deleteString = gson.toJson(getGoodsIdTypeArray());

        Log.e("deleteString", deleteString);

        NetClient.getInstance().getShopService(ShopInterface.class)
                .doRemoveCart(String.valueOf(currentUser.getUser_id()),
                        deleteString)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        flag = 2;
                        if (flag == 2) {//批量删除
                            mSelectState.clear();
                            totalPrice = 0.00;
                            shopTrolleyZongjiPianyi.setText("总计：￥" + df.format(totalPrice));
                            ToastHelper.toast("删除成功！");
                        }
                        getMyCart();
                        initAdapter();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

}
*/
